package com.amu.aidemo.android.audio

import android.content.Context
import android.media.MediaPlayer
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import kotlin.coroutines.resume

private const val TAG = "WakeWordSoundPlayer"

/**
 * 唤醒词提示音播放器
 * 用于播放唤醒词触发后的提示音（从 res/raw 目录加载）
 */
class WakeWordSoundPlayer(private val context: Context) {
    
    private var mediaPlayer: MediaPlayer? = null
    
    /**
     * 播放提示音（从 res/raw 资源）
     * @param resourceId 资源 ID，例如 R.raw.hi_yue
     * @return 播放是否成功
     */
    suspend fun playSoundFromResource(resourceId: Int): Boolean = withContext(Dispatchers.IO) {
        try {
            Log.d(TAG, "=== Starting wake word sound playback ===")
            Log.d(TAG, "Resource ID: $resourceId")
            
            // 释放旧的 MediaPlayer
            release()
            
            // 创建新的 MediaPlayer 并从资源加载
            Log.d(TAG, "Creating MediaPlayer from resource...")
            mediaPlayer = try {
                MediaPlayer.create(context, resourceId)
            } catch (e: Exception) {
                Log.e(TAG, "Exception creating MediaPlayer", e)
                null
            }
            
            if (mediaPlayer == null) {
                Log.e(TAG, "MediaPlayer.create() returned null - resource not found or invalid format")
                Log.e(TAG, "Make sure the file is in res/raw/ directory and is a valid audio format")
                return@withContext false
            }
            
            Log.d(TAG, "MediaPlayer created successfully")
            Log.d(TAG, "Audio duration: ${mediaPlayer?.duration}ms")
            
            // 使用协程等待播放完成
            suspendCancellableCoroutine { continuation ->
                mediaPlayer?.setOnCompletionListener {
                    Log.d(TAG, "Sound playback completed successfully")
                    continuation.resume(true)
                }
                
                mediaPlayer?.setOnErrorListener { mp, what, extra ->
                    Log.e(TAG, "MediaPlayer error during playback")
                    Log.e(TAG, "Error what: $what, extra: $extra")
                    continuation.resume(false)
                    true
                }
                
                // 开始播放
                try {
                    mediaPlayer?.start()
                    Log.d(TAG, "MediaPlayer.start() called successfully")
                } catch (e: Exception) {
                    Log.e(TAG, "Exception calling start()", e)
                    continuation.resume(false)
                }
                
                // 处理协程取消
                continuation.invokeOnCancellation {
                    Log.d(TAG, "Playback cancelled")
                    try {
                        mediaPlayer?.stop()
                    } catch (e: Exception) {
                        Log.e(TAG, "Error stopping MediaPlayer", e)
                    }
                    release()
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "Unexpected exception in playSoundFromResource", e)
            Log.e(TAG, "Exception type: ${e.javaClass.simpleName}")
            Log.e(TAG, "Exception message: ${e.message}")
            e.printStackTrace()
            false
        }
    }
    
    /**
     * 停止播放
     */
    fun stop() {
        try {
            mediaPlayer?.let {
                if (it.isPlaying) {
                    it.stop()
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "Error stopping sound", e)
        }
    }
    
    /**
     * 释放资源
     */
    fun release() {
        try {
            mediaPlayer?.release()
            mediaPlayer = null
            Log.d(TAG, "MediaPlayer released")
        } catch (e: Exception) {
            Log.e(TAG, "Error releasing MediaPlayer", e)
        }
    }
}
